import React from 'react';
import _ from 'underscore';

import { Scope } from 'lib/scopeFactory';
import { Warning } from 'lib/components/Notify.jsx';

import { defaultApi, defaultPostApi } from '../../apis/core-util';
import Str from '../../common/Str.js';

export default class EventScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.$state = {
      inProcessing: false,
      customGrid: {
        loading: true,
        data: []
      },
      predefinedGrid: {
        loading: true
      },
      targetObject: {
        event_id: props.target.id,
        cname: props.target.cname,
        visible: props.target.visible
      },
      errors: {
        customGrid: []
      }
    }; // $state

    this.dataTypeMapper = {
      'number': '数字',
      'string': '字符串',
      'list': '集合',
      'date': '日期',
      'datetime': '时间',
      'bool': '布尔值',
      'list': '集合'
    };

    this.$state.customCols = [
      {
        title: '属性名',
        key: 'name'
      }, {
        title: '中文名称',
        key: 'cname',
        render: (cellValue, rowData) => (
          <input
            type="text"
            className="input-text"
            onChange={ e => rowData.cname = e.target.value.trim() }
            defaultValue={ cellValue } />
        )
      }, {
        title: '数据类型',
        key: 'data_type',
        width: 80,
        formatter: item => this.dataTypeMapper[item]
      }, {
        title: '单位',
        key: 'unit',
        width: 75,
        render: (cellValue, rowData) => cellValue ? (
          <input
            type="text"
            className="input-text"
            style={{ width: '60px' }}
            onChange={ e => rowData.unit = e.target.value.trim() }
            defaultValue={ cellValue } />
        ) : null
      }
    ]; // customCols

    this.$state.predefinedCols = [
      {
        title: '属性名',
        key: 'name'
      }, {
        title: '中文名称',
        key: 'cname'
      }, {
        title: '数据类型',
        key: 'data_type',
        formatter: item => this.dataTypeMapper[item]
      }, {
        title: '字典',
        key: 'has_dict',
        formatter: item => item ? '有' : '无'
      }
    ]; // predefinedCols

    this.gridApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/event/${props.target.id}/properties`,
      cache: false,
      show_all: true
    });

    this.editApi = defaultPostApi({
      __url: `sd/${ BlueWare.appId }/api/event/${props.target.id}/meta`
    });
  } // constructor

  $property_changed(payload) {
    _.extend(this.$state.targetObject, payload.data);

    if (payload.data.cname) {
      if (Str.size(payload.data.cname) === 0) {
        this.$state.errors[payload.name] = '事件中文名不能为空';
      } else if (Str.size(payload.data.cname) > 100) {
        this.$state.errors[payload.name] = '事件中文名不能超出100个字符';
      } else {
        delete this.$state.errors[payload.name];
      }
    }

    this.emit();
  } // property_changed

  $save_event() {
    let hasError = _.chain(this.$state.errors.customGrid).compact().isEmpty().value();

    if (_.keys(this.$state.errors).length === 1 && hasError) {
      this.editApi
          .post(p => {
            let data = _.extend({}, this.$state.targetObject, this.$state.customGrid.data ? {
              property: _.map(this.$state.customGrid.data, item => ({
                property_id: item.id,
                cname: item.cname,
                unit: item.unit
              }))
            } : []);

            p.data = JSON.stringify(data);
            p.contentType = 'application/json';

            return p;
          })
          .progress(() => {
            this.$state.inProcessing = true;
            this.emit();
          })
          .fail(({status, responseJSON}) => {
            Warning(status === 409 ? responseJSON.error : '保存失败');
            this.$state.inProcessing = false;
            this.emit();
          })
          .done(() => this.viewInstance.close());
    }
  } // $save_event

  fetch() {
    this.gridApi
        .fetch()
        .progress(() => {
          this.$state.customGrid = {
            loading: true,
            data: []
          };
          this.$state.predefinedGrid = {
            loading: true
          };
          this.emit();
        })
        .fail(error => {
          this.$state.customGrid = { error };
          this.$state.predefinedGrid = { error };
        })
        .done((data, params) => {
          this.$state.customGrid = {
            data: _.chain(data.event)
                   .filter(item => item.name.indexOf('$') !== 0)
                   .value()
          };

          this.$state.predefinedGrid = {
            data: _.chain(data.event)
                   .filter(item => item.name.indexOf('$') === 0)
                   .value()
          };
        })
        .always(() => this.emit());
  } // fetch

  $load() {
    this.fetch();
  } // $load

  $custom_property_changed(payload) {
    let item = _.find(this.$state.customGrid.data, (data, index) => {
          return index === payload.index;
        });

    if (payload.name === 'cname') {
      if (Str.size(payload.data) === 0) {
        this.$state.errors.customGrid[payload.index] = {
          cname: '事件中文名不能为空'
        };
      } else if (Str.size(payload.data) > 100) {
        this.$state.errors.customGrid[payload.index] = {
          cname: '事件中文名不能超出100个字符'
        };
      } else {
        if (_.has(this.$state.errors.customGrid[payload.index], 'cname')) {
          this.$state.errors.customGrid = [
            ...this.$state.errors.customGrid.slice(0, payload.index),
            ...this.$state.errors.customGrid.slice(payload.index + 1)
          ];
        }
      }
    }

    item[payload.name] = payload.data;

    this.emit();
  }
}
